//
//  TTHMUserAccountViewModel.swift
//  WeiBo
//
//  Created by 涂永江 on 2017/6/7.
//  Copyright © 2017年 涂永江. All rights reserved.
//

import UIKit

class TTHMUserAccountViewModel: NSObject {

    //全局公共访问点
    static let sharedAccountModel = TTHMUserAccountViewModel()
    
    
    var accountModel :TTAccountModel?
    override init() {
        super.init()
      accountModel = TTAccountModel.solutionUserAccount()
        
    }
    
    var access_token:String?
    {
        guard let token = accountModel?.access_token else {
            return nil
        }
        
        if accountModel?.expiresDate?.compare(Date()) == .orderedDescending
        {
           return token
        
        }else
        {
        
        return nil
        }
        
    }
    
    var isaccess:Bool
    {
        let  isfalse = access_token != nil
        return isfalse
    }
    
    //获取token
    func requestToken(code:String?,isScuess:@escaping (Bool)->())
    {
        TTToolsManager.sharedManager.accessToken(code: code!, success: { (project, error) in
            if error != nil
            {
                isScuess(false)
                print("网络异常\(error!)")
                return
            }
            let dict = project as! [String:Any]
            
            let accountmodel = TTAccountModel(dict: dict)
            
            self.requestUerInfo(accountmodel: accountmodel, isScuess: isScuess)
        })
    }
    //获取用户信息
    func requestUerInfo(accountmodel:TTAccountModel,isScuess:@escaping (Bool)->())
    {
        
        let access_token = accountmodel.access_token
        let uid = accountmodel.uid
        TTToolsManager.sharedManager.accessUerinfo(access_token: access_token!, uid: uid) { (project, error) in
            
            if error != nil
            {
                isScuess(false)
                print("网络异常\(error!)")
                return
            }
            
            let dict = project as! [String:Any]
            let name = dict["name"] as? String
            let avatar_large = dict["avatar_large"] as? String
            
            //给模型赋值
            accountmodel.name = name
            accountmodel.avatar_large = avatar_large
            
            self.accountModel = accountmodel
            //保存模型对象 归档
            accountmodel.saveUserAccount()
            
            isScuess(true)
        }
        
        
    }
    
}
